package com.caszx.chargingpile.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alipay.sdk.app.PayTask;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.utils.DiskUser;
import com.app.utils.PayResult;
import com.app.utils.SignUtils;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.caszx.chargingpile.utils.ToastHelp;
import com.caszx.chargingpile.wxapi.WXEntryActivity;
import com.rey.material.app.DialogFragment;
import com.rey.material.widget.RadioButton;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;


/**
 * 账户充值
 */
public class UserRechargeActivity extends BaseTopBarNetActivity implements View.OnClickListener, IWXAPIEventHandler {


    private TextView txt_balance;
    private TextView txt_recharge;

    private RadioButton radio_paywallt;
    private RadioButton radio_payweixin;
    DecimalFormat decimalFormat = new DecimalFormat("##.##");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCenterTitle("账户充值");
        EventBus.getDefault().register(this);
    }

    public void onEvent(String action){
        if(EventBusAction.ACTION_USER_PAY_SUCCESS.equals(action)){
            finish();
        }
    }

    @Override
    protected void onLoad() {
        getUserInfo();
    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.activity_user_recharge, null);
        findView(view);
        return view;
    }


    protected void findView(View view) {
        txt_balance = (TextView) view.findViewById(R.id.txt_balance);
        txt_recharge = (TextView) view.findViewById(R.id.txt_recharge);

        radio_paywallt = (RadioButton) view.findViewById(R.id.radio_paywallt);
        radio_payweixin = (RadioButton) view.findViewById(R.id.radio_payweixin);

        view.findViewById(R.id.btn_price_01).setOnClickListener(this);
        view.findViewById(R.id.btn_price_02).setOnClickListener(this);
        view.findViewById(R.id.btn_price_03).setOnClickListener(this);
        view.findViewById(R.id.btn_price_04).setOnClickListener(this);
        view.findViewById(R.id.btn_price_05).setOnClickListener(this);
        view.findViewById(R.id.btn_price_06).setOnClickListener(this);

        view.findViewById(R.id.btn_recharge).setOnClickListener(this);

        radio_paywallt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radio_paywallt.setChecked(true);
                radio_payweixin.setChecked(false);
            }
        });


        radio_payweixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radio_payweixin.setChecked(true);
                radio_paywallt.setChecked(false);
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_price_01:
                txt_recharge.setText(R.string.recharge_price_20);
                break;
            case R.id.btn_price_02:
                txt_recharge.setText(R.string.recharge_price_50);
                break;
            case R.id.btn_price_03:
                txt_recharge.setText(R.string.recharge_price_100);
                break;

            case R.id.btn_price_04:
                txt_recharge.setText(R.string.recharge_price_200);
                break;
            case R.id.btn_price_05:
                txt_recharge.setText(R.string.recharge_price_300);
                break;

            case R.id.btn_price_06:
                txt_recharge.setText(R.string.recharge_price_500);
                break;

            case R.id.btn_recharge:
                //充值
                String price = txt_recharge.getText().toString();
                price = price.substring(0, price.length() - 1);
                recharge(price, radio_payweixin.isChecked() ? 2 : 1);
                break;
        }
    }

    private void getUserInfo() {
        HashMap<String, String> params = new HashMap<>();
        String token = DiskUser.getStringValueByKey(this, "token");
        params.put("token", token);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_DETAIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, getResources().getString(R.string.error_network), null);
                        //showSnackbarMsg(getResources().getString(R.string.error_network));
                        showErrorView();
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                showErrorView(resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    showContentView();
                                    txt_balance.setText(decimalFormat.format(response.optDouble("balance")) + "元");
                                } catch (JSONException e) {

                                }
                            }
                        }
                    }
                });
    }


    /**
     * 账户充值
     *
     * @param depositMoney 充值的钱 单位元
     * @param patmethod    1：支付宝 ，2：微信
     */
    private void recharge(String depositMoney, final int patmethod) {
        showProgressDialog("充值");
        String token = DiskUser.getStringValueByKey(this, "token");
        HashMap<String, String> params = new HashMap<>();
        params.put("depositMoney", depositMoney);
        params.put("patmethod", patmethod + "");
        params.put("token", token);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_RECHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, getResources().getString(R.string.error_network), null);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, resultJsonObject.optString("msg"), null);
                            } else {
                                try {
                                    DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, resultJsonObject.optString("msg"), null);
                                    if (patmethod == 1) {
                                        //支付宝支付
                                        pay(response);
                                    } else if (patmethod == 2) {
                                        //微信支付
                                        payWX(response);
                                    }

                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(UserRechargeActivity.this, getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }


    private IWXAPI api;


    /***
     * 初始化微信支付
     */
    private void intiWXPay() {
        if (api != null) return;
        api = WXAPIFactory.createWXAPI(this, WXEntryActivity.WEIXIN_APPID);
    }


    private void payWX(JSONObject json) {
        intiWXPay();
        Toast.makeText(this, "launch result = " + api.openWXApp(), Toast.LENGTH_LONG).show();
        try {
            if (null != json) {
                PayReq req = new PayReq();
                req.appId = WXEntryActivity.WEIXIN_APPID;
//                req.appId = json.getString("appid");
                req.partnerId = json.getString("partnerid");
                req.prepayId = json.getString("prepayid");
                req.nonceStr = json.getString("noncestr");
                req.timeStamp = json.getString("timestamp");
                req.packageValue = json.getString("package");
                req.sign = json.getString("sign");
                req.extData = "app data"; // optional
                SnackbarHelp.showSnackbarMsg(this, "正常调起支付...");
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                api.registerApp(WXEntryActivity.WEIXIN_APPID);
                handleIntent(getIntent());
                SnackbarHelp.showSnackbarMsg(this, "拉取微信...");
                boolean isSucess = api.sendReq(req);
                Toast.makeText(this, "isSucess = " + isSucess, Toast.LENGTH_LONG).show();
            } else {
                DialogHelp.showDialogOnlyMesg(this, "服务器请求错误", null);
            }
        } catch (Exception e) {
            DialogHelp.showDialogOnlyMesg(this, "异常", null);
        }
    }

    private void handleIntent(Intent paramIntent) {
        api.handleIntent(paramIntent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        ToastHelp.showMessage(this, "onReq ");
    }

    @Override
    public void onResp(BaseResp baseResp) {
        ToastHelp.showMessage(this, "onResp " + baseResp.errStr);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－支付开始－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－*/
    /**
     * 生成订单
     *
     * @param productId
     * @param num
     * @param payType
     */
//    private void createOrder(String productId, String num, String payType, JSONObject response) {
//        // 支付宝支付
//        if ("alipay".equals(payType) && Double.parseDouble(response.optString("paymoney"))/100 > 0) {
//            this.pay(response);
//        } else if ("wxpay".equals(payType)) { // 微信支付
//
//        }
//    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;


    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay(JSONObject response) {
        String partnerId = response.optString("partner");
        String private_key = response.optString("private_key");
        String seller = response.optString("seller");
        String ordersId = response.optString("ordersId");
        String title = response.optString("title");
        double totalFees = response.optDouble("totalFees");
        String content = response.optString("content");

        if (TextUtils.isEmpty(partnerId) || TextUtils.isEmpty(private_key) || TextUtils.isEmpty(seller)) {
            DialogHelp.showDialogTitleMeg(UserRechargeActivity.this, "需要配置PARTNER | RSA_PRIVATE| SELLER", "警告", new DialogHelp.DialogActionClickListener() {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    finish();
                }

                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                }
            });
            return;
        }
        String orderInfo = getOrderInfo(ordersId, partnerId, seller, title, content, totalFees);
        // 对订单做RSA 签名
        String sign = sign(orderInfo, private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                PayTask alipay = new PayTask(UserRechargeActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                subscriber.onNext(result);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.immediate())
                .subscribe(new Subscriber<String>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                        SnackbarHelp.showSnackbarMsg(UserRechargeActivity.this, "调用支付宝");
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String s) {
                        dissmissProgressDialog();
                        PayResult payResult = new PayResult(s);
                        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                        String resultInfo = payResult.getResult();
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
//                          DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付成功",null);
                            EventBus.getDefault().post(EventBusAction.ACTION_USER_PAY_SUCCESS);
                            finish();
                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, "支付结果确认中", null);
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                DialogHelp.showDialogOnlyMesg(UserRechargeActivity.this, "支付失败", null);
                            }
                        }
                    }
                });
    }


    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
    }

    /**
     * create the order info. 创建订单信息
     */
    public String getOrderInfo(String orderId, String partnerId, String seller, String subject, String body, double price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + partnerId + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + seller + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + orderId + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + ConstantUrl.URL_NOTIFY_PAY + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content, String privateKey) {
        return SignUtils.sign(content, privateKey);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－支付结束－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－*/

}
